package com.lsfb.duishangbaos.Login.ShopEnter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.lsfb.duishangbaos.R;
import com.lsfb.duishangbaos.Utils.GetJsonDataUtil;
import com.lsfb.duishangbaos.Utils.LittleUtils;
import com.lsfb.duishangbaos.Utils.NoDoubleClickUtils;
import com.lsfb.duishangbaos.Utils.PopWindowManager;
import com.lsfb.duishangbaos.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Administrator on 2017/5/10 0010.
 */
@ContentView(R.layout.aty_shop_enter2)
public class ShopEnterActivity extends LsfbActivity {

    /**
     * 商户名称
     */
    @ViewInject(R.id.aty_et_shop_name)
    private EditText et_shop_name;

    /**
     * 省市区
     */
    @ViewInject(R.id.aty_text_address)
    private TextView text_address;
    /**
     * 地址
     */
    @ViewInject(R.id.aty_et_address)
    private EditText et_address;
    /**
     * 坐标
     */
    @ViewInject(R.id.aty_text_coordinate)
    private TextView text_coordinate;
    /**
     * 商店类型
     */
    @ViewInject(R.id.aty_text_shop_type)
    private TextView text_shop_type;
    /**
     * 电话
     */
    @ViewInject(R.id.aty_et_phone)
    private EditText et_phone;
    /**
     * 姓名
     */
    @ViewInject(R.id.aty_et_name)
    private EditText et_name;
    /**
     * 身份证
     */
    @ViewInject(R.id.aty_et_id_card)
    private EditText et_id_card;
    /**
     * 推荐码
     */
    @ViewInject(R.id.aty_et_recommend_code)
    private EditText et_recommend_code;
    /**
     * 联系电话
     */
    @ViewInject(R.id.aty_text_phone)
    private TextView text_phone;

    private List<GetClaBean.ListBean> mList;

    /**
     * PopWindow管理类
     */
    private PopWindowManager replay;

    /**
     * RecyclerView的布局管理器
     */
    private RecyclerView.LayoutManager mlayoutManager;

    private ShopEnterAdapter adapter;


    /**
     * 定位经纬度
     */
    private String location = "";

    /**
     * 商户类别id
     */
    private String shop_type_id = "";

    /**
     * 商户类别名称
     */
    private String shop_type_name = "";

    private ArrayList<AddressBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AddressBean.ListsBeanX>> options1Items2 = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AddressBean.ListsBeanX.ListsBean>>> options1Items3 = new ArrayList<>();

    private String area_s = "";
    private String area_c = "";
    private String area_q = "";
    private String area = "";


    private String phone="";

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    text_shop_type.setText(shop_type_name);
                    break;
                case 2000:
                    text_coordinate.setText(location);
                    break;
                case 3000:
                    text_address.setText(area);
                    break;
            }
        }
    };

    @Override
    public void initView() {
        LittleUtils.setsimpletitlebar(this, "商户入驻");
        mList = new ArrayList<>();
        adapter = new ShopEnterAdapter(this, mList, R.layout.item_shop_type);


        String JsonData = new GetJsonDataUtil().getJson(this, "region.json");
        ArrayList<AddressBean> list = parseData(JsonData);

        options1Items = list;

        for (int i = 0; i < list.size(); i++) {
            ArrayList<AddressBean.ListsBeanX> citylist = new ArrayList<>();
            ArrayList<ArrayList<AddressBean.ListsBeanX.ListsBean>> arealist = new ArrayList<>();

            citylist.addAll(list.get(i).getLists());
            for (int j = 0; j < list.get(i).getLists().size(); j++) {
                ArrayList<AddressBean.ListsBeanX.ListsBean> City_AreaList = new ArrayList<>();
                if (list.get(i).getLists().get(j).getLists() == null || list.get(i).getLists().get(j).getLists().size() == 0) {
                    City_AreaList.add(new AddressBean.ListsBeanX.ListsBean());
                } else {
                    City_AreaList.addAll(list.get(i).getLists().get(j).getLists());
                }
                arealist.add(City_AreaList);
            }

            options1Items2.add(citylist);

            options1Items3.add(arealist);
        }

        LsfbLog.e("数据装在完成");
    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_address_select, R.id.aty_coordinate_get, R.id.aty_type_select, R.id.aty_btn_post})
    public void onClick(View view) {
        switch (view.getId()) {
            //省市区选择
            case R.id.aty_address_select:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_shop_name.getWindowToken(), 0);
                ini();
                break;
            //坐标获取
            case R.id.aty_coordinate_get:
                InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.hideSoftInputFromWindow(et_shop_name.getWindowToken(), 0);
                imm1.hideSoftInputFromWindow(et_address.getWindowToken(), 0);
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    startActivity(new Intent(this, LocationActivity.class));
                }
                break;
            //类别选择
            case R.id.aty_type_select:
                replay = new PopWindowManager(ShopEnterActivity.this, R.layout.pop_shop_type) {
                    @Override
                    public void onViewLister(View contentView, final PopWindowManager manager) {

                        final ImageView imageView = (ImageView) contentView.findViewById(R.id.pop_img_exit);
                        final RecyclerView dish_list = (RecyclerView) contentView.findViewById(R.id.dish_list);
                        final RelativeLayout RelativeLayout = (RelativeLayout) contentView.findViewById(R.id.RelativeLayout);

                        mlayoutManager = new LinearLayoutManager(ShopEnterActivity.this);//布局模式为listview方式
                        dish_list.setLayoutManager(mlayoutManager);
                        dish_list.setAdapter(adapter);

                        RelativeLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                manager.hideWindow();
                            }
                        });

                        imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                manager.hideWindow();
                            }
                        });

                    }
                };
                replay.showWindowsCenter(this.getWindow().getDecorView());
                break;
            //申请提交
            case R.id.aty_btn_post:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    busJoin();
                }
                break;

        }
    }

    public void ini() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
//                String tx = options1Items.get(options1).getId() +" "+
//                        options1Items2.get(options1).get(options2).getId() +" "+
//                        options1Items3.get(options1).get(options2).get(options3).getId();
//                Toast.makeText(ShopEnterActivity.this, tx, Toast.LENGTH_SHORT).show();

                area_s = String.valueOf(options1Items.get(options1).getId());
                area_c = String.valueOf(options1Items2.get(options1).get(options2).getId());
                area_q = String.valueOf(options1Items3.get(options1).get(options2).get(options3).getId());
                area = options1Items.get(options1).getName() + options1Items2.get(options1).get(options2).getName() + options1Items3.get(options1).get(options2).get(options3).getName();
                handler.sendEmptyMessage(3000);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options1Items2, options1Items3);//三级选择器
        pvOptions.show();
    }


    /**
     * 商家入驻
     */
    public void busJoin() {

        if (et_shop_name.getText().toString().isEmpty()) {
            SN.SnackShow(text_phone, "请输入店铺名称");
            return;
        }
        if (et_address.getText().toString().isEmpty()) {
            SN.SnackShow(text_phone, "请输入店铺地址");
            return;
        }
        if (et_phone.getText().toString().isEmpty()) {
            SN.SnackShow(text_phone, "请输入电话号码");
            return;
        }
        if (et_name.getText().toString().isEmpty()) {
            SN.SnackShow(text_phone, "请输入姓名");
            return;
        }
        if (et_id_card.getText().toString().isEmpty()) {
            SN.SnackShow(text_phone, "请输入身份证号码");
            return;
        }
        if (location.isEmpty()) {
            SN.SnackShow(text_phone, "请选择坐标");
            return;
        }
        if (shop_type_id.isEmpty()) {
            SN.SnackShow(text_phone, "请选择商家内别");
            return;
        }
        if (area_s.isEmpty() || area_c.isEmpty() || area_q.isEmpty()) {
            SN.SnackShow(text_phone, "请选择省市区");
            return;
        }


        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("busname", et_shop_name.getText().toString());//店铺名称
        hashMap.put("area_s", area_s);//省id
        hashMap.put("area_c", area_c);//市id
        hashMap.put("area_q", area_q);//区id
        hashMap.put("area", area);//省市区名称
        hashMap.put("addr", et_address.getText().toString());//地址
        hashMap.put("axis", location);//经纬度
        hashMap.put("cla", shop_type_id);//商家分类id
        hashMap.put("tel", et_phone.getText().toString());//电话
        hashMap.put("name", et_name.getText().toString());//姓名
        hashMap.put("idcard", et_id_card.getText().toString());//身份证
        if (!et_recommend_code.getText().toString().isEmpty()) {
            hashMap.put("recode", et_recommend_code.getText().toString());//推荐码
        }
        new BaseInternet().getData(URLString.BUSJOIN, hashMap, BusJoinBean.class, new BusJoinEvent<BusJoinBean>(), false);
    }

    @EventAnnotation
    public void BusJoinEvent(BusJoinEvent<BusJoinBean> event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this, event.getMsg());
                finish();
                break;
            default:
                SN.SnackShow(text_phone, event.getMsg());
                break;
        }
    }

    @Override
    public void initData() {
        getCla();
        getPhone();
    }

    /**
     * 获取商家分类
     */
    public void getCla() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.CLA, hashMap, GetClaBean.class, new GetClaEvent<GetClaBean>(), false, true);
    }

    @EventAnnotation
    public void GetClaEvent(GetClaEvent<GetClaBean> event) {
        switch (event.getCode()) {
            case 200:
                mList.clear();
                mList.addAll(event.getData().getList());
                adapter.notifyDataSetChanged();
                break;
            default:
//                SN.SnackShow(text_phone, event.getMsg());
                break;
        }
    }

    /**
     * 得到定位点
     *
     * @param event
     */
    @EventAnnotation
    public void LocationEvent(LocationEvent event) {
        location = event.getData();
        handler.sendEmptyMessage(2000);
    }

    /**
     * 商户类别选择回调
     *
     * @param event
     */
    @EventAnnotation
    public void ShopTypeClickEvent(ShopTypeClickEvent event) {
        replay.hideWindow();
        shop_type_id = event.getData().getId();
        shop_type_name = event.getData().getName();
        handler.sendEmptyMessage(1000);
    }

    public ArrayList<AddressBean> parseData(String result) {//Gson 解析
        ArrayList<AddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), AddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LsfbLog.e(e.getMessage());
        }
        return detail;
    }

    public void getPhone() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.TEL, hashMap, GetPhoneBean.class, new GetPhoneEvent<GetPhoneBean>(), true, false);
    }

    @EventAnnotation
    public void GetPhoneEvent(GetPhoneEvent<GetPhoneBean> event) {
        switch (event.getCode()) {
            case 200:
                phone=event.getData().getTel();
                text_phone.setText(phone);
                break;
            default:
                SN.SnackShow(text_phone, event.getMsg());
                break;
        }
    }

}
